#!/usr/bin/env python
# don't like coding:utf8
import re
import sys
import tempfile
import os
import subprocess
from random import randint
from time import time
from tqdm import tqdm

def bblue(s):
    return '\033[1;34m' + str(s) + '\033[0m'

def run_strategy(*args, input=None, output=None):
    """
    input/output是文件名, 一定要传
    """
    cmd = f'./bin/CodeCraft-2021 <{input} >{output} ' + ' '.join(map(lambda a:str(a), args))
    #print(cmd)
    subprocess.getstatusoutput(cmd)

def judge(input, output):
    cmd = '../judge %s %s' % (input, output)
    #print(cmd)
    rc,out = subprocess.getstatusoutput(cmd)
    lines = out.split('\n')
    cost = int(re.search(r'\d+', lines[0]).group())
    migration = int(re.search(r'\d+', lines[1]).group())
    return cost,migration

def run(param):
    """运行strategy和判题程序，返回cost,migration"""
    input1 = '../data2/training-1.txt'
    input2 = '../data2/training-2.txt'
    _,output1 = tempfile.mkstemp()
    _,output2 = tempfile.mkstemp()
    t1 = time()
    run_strategy(*param, input=input1, output=output1)
    t2 = time()
    ta = round(t2-t1,2)
    t1 = time()
    run_strategy(*param, input=input2, output=output2)
    t2 = time()
    tb = round(t2-t1,2)
    cost1,migration1 = judge(input1, output1)
    cost2,migration2 = judge(input2, output2)
    os.remove(output1)
    os.remove(output2)
    return (cost1, migration1, ta), (cost2, migration2, tb)

def p1():
    filename='./Param_1.txt'
    with open(filename,'w') as f:
    	for p1 in tqdm(range(100)):
            ra, rb = run([p1,14,42,20,8,24,105,42,0.06,0.195])
            f.write('param: %d 14 42 20 8 24 105 42 0.06 0.195 cost: %d+%d=%s' % (p1,ra[0], rb[0], bblue(ra[0]+rb[0])))
        

def p2():
    for p2 in tqdm(range(100)):
        run(8,p2,65,31,6,11,76,46,0.06,0.17,filename='./record2.txt')
def p3():
    for p3 in tqdm(range(500)):
        run(8,17,p3,31,6,11,76,46,0.06,0.17,filename = './record3.txt')
def p4():
    for p4 in tqdm(range(500)):
        run(5,14,42,p4,8,24,105,42,0.06,0.195,filename = './record4.txt')
def p5():
    for p5 in tqdm(range(100)):
        run(5,14,42,20,p5,11,76,46,0.06,0.17,filename = './record5.txt')
def p6():
    for p6 in tqdm(range(100)):
        run(5,14,42,20,7,p6,105,42,0.06,0.195,filename = './record6.txt')
def p7():
    for p7 in tqdm(range(500)):
        run(8,17,65,31,6,11,p7,46,0.06,0.17,filename = './record7.txt')
def p8():
    for p8 in tqdm(range(500)):
        run(8,17,65,31,6,11,76,p8,0.06,0.17,filename = './record8.txt')
def p9():
    for p9 in tqdm(range(0,1,0.001)):
        run(8,17,65,31,6,11,76,46,p9,0.17,filename = './record9.txt')
def p10():
    for p10 in tqdm(range(0,1,0.001)):
        run(8,17,65,31,6,11,76,46,0.06,p10,filename = './record10.txt')

p1()


